package com.cuitrip.business.bill;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.cuitrip.apiservice.OrderBusiness;
import com.cuitrip.apiservice.ServiceBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.bill.model.BankInfo;
import com.cuitrip.business.bill.model.UserAccount;
import com.cuitrip.business.bill.model.UserAccounts;
import com.cuitrip.business.tripservice.model.SelectMenu;
import com.cuitrip.business.tripservice.ui.SelectMenuFragment;
import com.cuitrip.component.choicedialog.ChoiceDialog;
import com.cuitrip.service.R;
import com.lab.adapter.IAdapterData;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragment;
import com.lab.component.list.CTRecyclerView;
import com.lab.component.list.simple.CTSimpleRecyclerAdapter;
import com.lab.component.list.simple.CTSimpleViewHolder;
import com.lab.jumper.FragmentJumper;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.rx.bus.RxBus;
import com.lab.utils.ImageHelper;
import com.lab.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by sheena on 16/4/27.
 */
public class AccountsFragment<T extends IAdapterData> extends CustomUiFragment implements IProxyCallback {

    public static final int ACCOUNT_PAYPAL = 0;
    public static final int ACCOUNT_BANK = 1;
    public static final int TYPE_RECYCLERVIEW=0;
    public static final int TYPE_ITEMLAYOUT=1;
    @Bind(R.id.rv_accouts)
    CTRecyclerView mCtRecyclerView;
    private ApiProxy apiProxy = new ApiProxy(this);
    private ArrayList<IAdapterData> accountList = new ArrayList<>();
    private CTSimpleRecyclerAdapter mAdapter;
    private int pos=-1;
    private Subscription subscription;

    public static AccountsFragment newInstance() {
        AccountsFragment accountsFragment = new AccountsFragment();
        Bundle bundle = new Bundle();
        accountsFragment.setArguments(bundle);
        return accountsFragment;
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mLeftStyle = CustomUiConfig.AreaStyle.ICON_STYLE;
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        config.mTopbarMiddleAreaName = getString(R.string.wallet_account_operate_add);
        return config;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState, R.layout.fragment_add_accounts);
    }

    @Override
    public void initView() {
        ButterKnife.bind(this, getView());
        subscription = RxBus.getDefault().toObservable().subscribe(new Action1<Object>() {
            @Override
            public void call(Object o) {
                if (o instanceof AccountAddEvent) {
                    OrderBusiness.getUserAccounts(apiProxy);
                    showNoCancelDialog();
                }

            }
        });
    }


    @Override
    public void initData() {
        OrderBusiness.getUserAccounts(apiProxy);
        showNoCancelDialog();
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(AppCoreRuntime.context, LinearLayoutManager.VERTICAL, false);
        mCtRecyclerView.setLayoutManager(mLayoutManager);
        mCtRecyclerView.hideProgress();
        mAdapter = new CTSimpleRecyclerAdapter<IAdapterData>(AppCoreRuntime.context,accountList) {
            @Override
            public int getItemLayoutId(int viewType) {
                if (viewType == TYPE_RECYCLERVIEW){
                    return R.layout.item_fragment_accounts;
                }else {
                    return R.layout.item_accounts_add;
                }
            }

            @Override
            public int getItemViewType(int position) {
                if (position == getItemCount()-1){
                    return TYPE_ITEMLAYOUT;
                }else{
                    return TYPE_RECYCLERVIEW;
                }
            }


            @Override
            public void onNewViewHolder(CTSimpleViewHolder viewHolder, ViewGroup parent, int viewType) {
            }

            @Override
            public void bindData(final CTSimpleViewHolder holder, final int position, final IAdapterData item) {
                if (item instanceof UserAccount ) {
                    final UserAccount userAccount = (UserAccount) item;
                    ImageView icon = holder.getView(R.id.icon);
                    ImageHelper.displayCtImage(userAccount.getAccountIcon(), icon, null);
                    TextView bankName = holder.getView(R.id.bank_name);
                    bankName.setText(userAccount.getAccountAbbr());
                    TextView accountNO = holder.getView(R.id.account_no);
                    accountNO.setText(userAccount.getAccountNumber());

                    holder.getView().setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            ChoiceDialog choiceDialog = ChoiceDialog.getInstance();
                            choiceDialog.setDialogTitle(getResources().getString(R.string.wallet_account_delete_confirm)+"("+userAccount.getAccountNumber()+")");
                            choiceDialog.setDialogMessageVisibility(false);
                            choiceDialog.setDialogCoupleStyleSetting(
                                    getResources().getString(R.string.operation_yes),
                                    getResources().getString(R.string.operation_no), new ChoiceDialog.DialogStyleCoupleCallback() {
                                        @Override
                                        public boolean onPositiveButtonClick() {
                                            ServiceBusiness.deleteUserAccount(apiProxy,String.valueOf(userAccount.getUserAccountId()));
                                            pos=position;
                                            return false;
                                        }

                                        @Override
                                        public boolean onNegativeButtonClick() {
                                            return false;
                                        }
                                    });
                            showDialogFragment(choiceDialog);
                            return true;
                        }
                    });
                }else if(item instanceof BankInfo){
                    holder.getView().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            addAccount();
                        }
                    });
                }
            }
        };

        mCtRecyclerView.setAdapter(mAdapter);

    }


    private void addAccount() {
        SelectMenuFragment selectMenuFragment = new SelectMenuFragment();
        List<SelectMenu> selectMenuList = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            SelectMenu selectMenu = new SelectMenu();
            selectMenu.key = String.valueOf(i);
            switch (i) {
                case ACCOUNT_PAYPAL:
                    selectMenu.value = getString(R.string.account_paypal);
                    break;
                case ACCOUNT_BANK:
                    selectMenu.value = getString(R.string.wallet_account_type_bank);
            }

            selectMenuList.add(selectMenu);
        }
        selectMenuFragment.setTitle(getString(R.string.wallet_account_operate_add));
        selectMenuFragment.setSelectMenuList(selectMenuList);
        showDialogFragment(selectMenuFragment);
        selectMenuFragment.setResultListener(new SelectMenuFragment.OnDataSelectBackListener() {
            @Override
            public void onSelect(SelectMenu selectMenu) {
                int i = Integer.parseInt(selectMenu.key);
                if (i == ACCOUNT_PAYPAL) {
                    FragmentJumper.addFragment(getHostActivity().getCustomSelfFragmentManager(), R.id.container, new BindPayPalFragment(), BindPayPalFragment.class.getName(), true);
                } else if (i == ACCOUNT_BANK) {
                    FragmentJumper.addFragment(getHostActivity().getCustomSelfFragmentManager(), R.id.container, new AddBankAccountFragment(), AddBankAccountFragment.class.getName(), true);
                }

            }
        });
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        if (!isAdded()){
            return false;
        }
        CtApiResponse response = (CtApiResponse) result.getData();
        if (response.isResponseNormal()) {
            if (response.getApiName().equals(ApiManager.GET_USER_ACCOUNTS)) {
                if (response.result instanceof UserAccounts) {
                    UserAccounts userAccounts = (UserAccounts) response.result;
                    accountList.clear();
                    accountList.addAll(userAccounts.getList());
                    accountList.add(new BankInfo());
                    mAdapter.notifyDataSetChanged();
                    hideNoCancelDialog();
                    return false;
                }
            }else if (response.getApiName().equals(ApiManager.DELETE_USER_ACCOUNT)){
                accountList.remove(pos);
                mAdapter.notifyDataSetChanged();

            }
        } else {
            hideNoCancelDialog();
            ToastUtil.toast(getContext(), response.msg, 0);
            return false;
        }
        return false;
    }

    @Override
    public void onTopbarLeftPress() {
        onBackPressed();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (!subscription.isUnsubscribed()){
            subscription.unsubscribe();
        }
    }
}
